package com.fly.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fly.constant.MessageConstant;
import com.fly.constant.RedisConstant;
import com.fly.entity.PageResult;
import com.fly.entity.QueryPageBean;
import com.fly.entity.Result;
import com.fly.pojo.CheckGroup;
import com.fly.pojo.Setmeal;
import com.fly.service.SetmealService;
import com.fly.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

/*
* 套餐管理
* */
@RequestMapping("/setmeal")
@RestController
public class SetmealController {
    //使用JedisPool操作Redis服务
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private SetmealService setmealService;

    //文件上传
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile){
        //获取原始文件名
        String originalFilename = imgFile.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");//获取原始文件名中最后一个点的索引位置
        String s = originalFilename.substring(index);//获取到文件格式   .jpg字符串
        //为了保证每次上传的文件名称不一样,用UUID生成新的文件名
        String fileName = UUID.randomUUID().toString() + s;

        try {
            //将文件上传到七牛云服务器
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);

            //将图片上传到七牛云服务器，图片名称保存到redis中
            //                                     参数1： 集合名称        参数2：缓存的数据
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.PIC_UPLOAD_FAIL);
        }

        //上传成功返回文件名
        return new Result(true,MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
    }

    //添加套餐
    @RequestMapping("/add")
    public Result add(Integer []checkgroupIds, @RequestBody Setmeal setmeal){

        try {
            setmealService.add(checkgroupIds, setmeal);

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }
        return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
    }


    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult= setmealService.findPage(queryPageBean);
        return pageResult;
    }

}